<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// 每天凌晨4点执行
class Upfiletowx extends CI_Controller {

	public function index(){
		set_time_limit(0);
		$this->load->model('Wxident_model', 'Mwxident');
		$access_token = $this->Mwxident->get_access_token();
		$base_url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={$access_token}&type=";
		
		$where = 'type in(?, ?, ?)';
		$cond = array(3, 4, 5);
		$this->load->model('Material_model', 'Mmaterial');
		$size = 20;
		for ($i = 0; ;$i ++){
			$offset = $size * $i;
			$re_list = $this->Mmaterial->get_list($where, $cond, $offset, $size);
			if (empty($re_list)){
				break;
			}
			$now_time = time();
			foreach ($re_list as $material){
				$time_differ = $now_time - $material['media_id_time'];
				if ($time_differ < 60 * 60 * 24 * 2){
					continue;
				}
				
				switch ($material['type']){
					case 3:
						// 图片
						$typestr = 'image';
						$file = BASEWEBPATH . $material['picurl'];
						break;
					case 4:
						// 语音
						$typestr = 'voice';
						$file = BASEWEBPATH . $material['voiceurl'];
						break;
					case 5:
						// 视频
						$typestr = 'video';
						$file = BASEWEBPATH . $material['videourl'];
						break;
					default:
						continue;
				}
				
				$up_url = $base_url . $typestr;
				$re_up = $this->Mmaterial->upload_to_wx($up_url, $file, $typestr);
				$re_arr = json_decode($re_up, true);
				
				if (isset($re_arr['media_id']) && isset($re_arr['created_at'])){
					$updata = array(
							'media_id' => $re_arr['media_id'],
							'media_id_time' => $re_arr['created_at']
						);
					$where = 'id=?';
					$cond = array($material['id']);
					$this->Mmaterial->update($updata, $where, $cond);
				}elseif (isset($re_arr['errcode']) && $re_arr['errcode'] == 40001){
					// 重新获取access_token
					$re_arr['errmsg'];
				}else{
					// 处理上传失败
				}
			}
			
		}
	}
	
}
